﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using System.Text;
using Sale_Operation;
using Sale_Common;
using Sale_Model;
using SaleSystem;
using ExtAspNet;


namespace SaleSystem.Business
{
    public partial class frm_SaleBillEdit : PageBase
    {
        #region Page Event
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                tb_SBill_Cust_Id.OnClientTrigger2Click = win_Content.GetSaveStateReference(tb_SBill_Cust_Id.ClientID, this.hf_SBill_Cust_Id.ClientID)
                         + win_Content.GetShowReference("~/ComPage/frm_CustomerChooseList.aspx");
                tb_SBDeta_PInfo_Id.OnClientTriggerClick = win_Content2.GetSaveStateReference(tb_SBDeta_PInfo_Id.ClientID, this.hf_SBDeta_PInfo_Id.ClientID, this.nb_SBDeta_Count.ClientID, this.nb_SBDeta_Price.ClientID, this.nb_SBDeta_Money.ClientID, this.nb_SBDeta_Price.ClientID)
                                        + win_Content2.GetShowReference("~/ComPage/frm_ProductChooseList.aspx?PInfo_Id=");
                //tb_SBDeta_PInfo_Id.OnClientTriggerClick = win_Content.GetSaveStateReference(tb_SBDeta_PInfo_Id.ClientID, this.hf_SBDeta_PInfo_Id.ClientID)
                //         + win_Content.GetShowReference("~/ComPage/frm_ProductChooseList.aspx?PInfo_Id=" + this.tb_SBDeta_PInfo_Id.GetValueReference());

                InitControl();
                GetAndBind();
               

            }
        }
        protected void ddl_SBill_PayTypeSelectedChanged(object obj, EventArgs e)
        {
            SysConfig SM = new SysConfig();
            if (this.ddl_SBill_PayType.SelectedValue == "1")//现金
            {
                SM.SConf_Id = 4;
            }
            else
                SM.SConf_Id = 5;
            SysConfigOp op = new SysConfigOp();
            op.GetConfig(SM);
            this.ddl_SBill_AList_Id.SelectedValue = SM.SConf_Value;
        }
        protected void nb_SBill_TaxMoney_TextChanged(object sender, EventArgs e)
        {
            this.nb_SBill_RealMoney.Text = (ValueHandler.GetDecNumberValue(this.nb_SBill_Money.Text) + ValueHandler.GetDecNumberValue(this.nb_SBill_TaxMoney.Text)).ToString();
            
        }
        protected void Trigger1_Click(object sender, EventArgs e)
        {
            tb_SBill_Cust_Id.Text = "";
            hf_SBill_Cust_Id.Text = "";
        }
        protected void bnSave_Click(object sender, EventArgs e)
        {
            //如果是修改，保存前先校验下该单据状态是否已经被入库了，如果入库了则不能修改
            if (this.Id != 0)
            {
                SModel.SBill_Id = this.Id;
                Manager.GetModel(SModel);
                if (SModel.SBill_State == 1)
                {
                    ExtAspNet.Alert.Show("该销售单已经结算，不能修改！", "操作提示！", MessageBoxIcon.Warning);
                    return;
                }
            } 
           
            bool blHasExists = Manager.HasExists(SModel);
            if (blHasExists)
            {
                ExtAspNet.Alert.ShowInTop("销售单编码已经存在，请重新输入！", MessageBoxIcon.Information);
            }
            else
            {
                List<String> LSCheckProduct = Manager.CheckStore(SModel, dtDetail);
                if (LSCheckProduct.Count <= 0)
                {
                    SModel.CreateMan = LinkService.GetCurrentUser().SUser_Id;
                    SModel.CreateTime = System.DateTime.Now;
                    SModel.State = 1;
                    SModel.SBill_AList_Id = ValueHandler.GetIntNumberValue(this.ddl_SBill_AList_Id.SelectedValue);
                    SModel.SBill_Code = this.tb_SBill_Code.Text;
                    SModel.SBill_Code2 = this.tb_SBill_Code2.Text;
                    SModel.SBill_Cust_Id = ValueHandler.GetIntNumberValue(this.hf_SBill_Cust_Id.Text);
                    SModel.SBill_Date = DateTime.Parse(this.dp_SBill_Date.Text);
                    SModel.SBill_Money = ValueHandler.GetDecNumberValue(this.nb_SBill_Money.Text);
                    SModel.SBill_PayType = ValueHandler.GetIntNumberValue(this.ddl_SBill_PayType.SelectedValue);
                    SModel.SBill_RealMoney = ValueHandler.GetDecNumberValue(this.nb_SBill_Money.Text) + ValueHandler.GetDecNumberValue(this.nb_SBill_TaxMoney.Text);
                    SModel.SBill_Remark = this.tb_SBill_Remark.Text;
                    SModel.SBill_Type = ValueHandler.GetIntNumberValue(this.ddl_SBill_Type.SelectedValue);
                    SModel.SBill_User = ValueHandler.GetIntNumberValue(this.ddl_SBill_User.SelectedValue);
                    SModel.State = 1;
                    SModel.SBill_TaxMoney = ValueHandler.GetDecNumberValue(this.nb_SBill_TaxMoney.Text);
                    bool blRes = Manager.Save(SModel, dtDetail);
                    if (blRes)
                        ExtAspNet.PageContext.RegisterStartupScript(ExtAspNet.ActiveWindow.GetHidePostBackReference(LinkService.RefreshString));

                    else
                        ExtAspNet.Alert.ShowInTop("销售单信息编辑失败！", MessageBoxIcon.Error);
                }
                else //库存不满足
                {
                    StringBuilder sbSql = new StringBuilder();
                    for (int i = 0; i < LSCheckProduct.Count; i++)
                    {
                        if(i==LSCheckProduct.Count-1)
                            sbSql.Append(LSCheckProduct[i]);
                        else
                            sbSql.Append(LSCheckProduct[i]+",");
                    }
                    ExtAspNet.Alert.ShowInTop("产品：" + sbSql.ToString() + "库存不足，无法创建销售单！", MessageBoxIcon.Error);

                }
            }
        }
        /// <summary>
        /// 添加产品明细
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAdd_Click(object sender, EventArgs e)
        {

            if (hf_SBDeta_PInfo_Id.Text.Trim() == "")
            {
                ExtAspNet.Alert.Show("请先选中产品后再做此操作！", "提示！", MessageBoxIcon.Warning);
                return;
            }
            else
            {
                DataTable dt = dtDetail;


                ProductInfoOp ProductManager = new ProductInfoOp();
                ProductInfo SM = new ProductInfo();
                SM.PInfo_Id = ValueHandler.GetIntNumberValue(hf_SBDeta_PInfo_Id.Text);
                //判断单据中是否存在该产品
                DataView dv = new DataView(dt);
                dv.RowFilter = "SBDeta_PInfo_Id=" + SM.PInfo_Id.ToString() + " AND SBDeta_Id<>" + SBDeta_Id;
                if (dv.Count > 0)
                {
                    ExtAspNet.Alert.Show("单据中已经存在该产品信息！", "提示！", MessageBoxIcon.Warning);
                    return;
                }
                DataRow dr = null;
                if (this.btnAdd.Text == "添加")
                {
                    dr = dt.NewRow();
                    dt.Rows.Add(dr);

                }
                else
                {
                    DataView dv0 = new DataView(dt);
                    dv0.RowFilter = "SBDeta_Id=" + SBDeta_Id;
                    if (dv0.Count > 0)
                        dr = dv0[0].Row;
                }
                ProductManager.GetModel(SM);
                dr["PInfo_Code"] = SM.PInfo_Code;
                dr["PInfo_Name"] = SM.PInfo_Name;
                dr["SBDeta_PInfo_Id"] = this.hf_SBDeta_PInfo_Id.Text;
                dr["SBDeta_SBill_Id"] = this.Id;
                dr["SBDeta_Count"] = ValueHandler.GetIntNumberValue(this.nb_SBDeta_Count.Text);
                dr["SBDeta_Price"] = ValueHandler.GetDecNumberValue(this.nb_SBDeta_Price.Text);
                dr["SBDeta_Money"] = ValueHandler.GetDecNumberValue(this.nb_SBDeta_Price.Text) * ValueHandler.GetDecNumberValue(this.nb_SBDeta_Count.Text);
   
                //获取产品类别
                ProductSortOp sortManager = new ProductSortOp();
                ProductSort sortSM = new ProductSort();
                sortSM.PSort_ID = SM.PInfo_PSort_ID;
                sortManager.GetModelById(sortSM);
                dr["PSort_Name"] = sortSM.PSort_Name;
                gv_List.DataSource = dtDetail;
                gv_List.DataBind();
                gv_List.RecordCount = dtDetail.Rows.Count;
                //计算总数量及总金额
                this.nb_SBill_Money.Text = dtDetail.Compute("sum(SBDeta_Money)", "").ToString();
                this.nb_SBill_RealMoney.Text=(ValueHandler.GetDecNumberValue(this.nb_SBill_Money.Text)+ValueHandler.GetDecNumberValue(this.nb_SBill_TaxMoney.Text)).ToString();
                ClearContent();
            }
        }
        protected void bnInput_Click(object sender, EventArgs e)
        { 
            SModel.SBill_Id = this.Id;
            Manager.GetModel(SModel);
            if (SModel.SBill_PayType ==-1)
            {
                ExtAspNet.Alert.Show("该单据结算方式并未保存，请保存后再结算！", "操作提示！", MessageBoxIcon.Warning);
                return;
            }
            if (SModel.SBill_AList_Id == 0 || SModel.SBill_AList_Id == -1)
            {
                ExtAspNet.Alert.Show("该单据结算账户并未保存，请保存后再结算！", "操作提示！", MessageBoxIcon.Warning);
                return;
            }
            if (SModel.SBill_State == 1)
            {
                ExtAspNet.Alert.Show("该销售单已经结算，不能再次结算！", "操作提示！", MessageBoxIcon.Warning);
            }
            else
            {
                bool blRes = Manager.JS(SModel);
                if (blRes)
                {
                    PageContext.RegisterStartupScript(ExtAspNet.Alert.GetShowInTopReference("结算完成！", "操作提示！", MessageBoxIcon.Information) + ExtAspNet.ActiveWindow.GetHidePostBackReference(LinkService.RefreshString));
                }
                else
                {
                    ExtAspNet.Alert.Show("结算失败！","操作提示！", MessageBoxIcon.Error);
                }
                }
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            ClearContent();

        }
        private void ClearContent()
        {
            this.tb_SBDeta_PInfo_Id.Text = "";
            this.hf_SBDeta_PInfo_Id.Text = ""; 
            this.nb_SBDeta_Count.Text = "1";
            this.nb_SBDeta_Money.Text = "";
            this.nb_SBDeta_Price.Text = "";
            SBDeta_Id = 0;
            this.btnAdd.Text = "添加";
            this.btnAdd.Icon = Icon.Add;
            this.btnCancle.Hidden = true;
        }
        protected void gv_List_RowCommand(object sender, ExtAspNet.GridCommandEventArgs e)
        {
            if (e.CommandName.ToLower() == "delete")
            {
                DataView dv = new DataView(dtDetail);
                SBDeta_Id = ValueHandler.GetIntNumberValue(gv_List.DataKeys[e.RowIndex][0]);
                dv.RowFilter = "SBDeta_Id=" + SBDeta_Id;
                if (dv.Count > 0)
                {
                    dv[0].Delete();
                }
                dtDetail.AcceptChanges();
                gv_List.DataSource = dtDetail.DefaultView;
                gv_List.DataBind();
                gv_List.RecordCount = dtDetail.Rows.Count;
                //计算总数量及总金额
               
                ClearContent();
            }
            else if (e.CommandName.ToLower() == "edit")
            {
                DataView dv = new DataView(dtDetail);
                SBDeta_Id = ValueHandler.GetIntNumberValue(gv_List.DataKeys[e.RowIndex][0]);
                dv.RowFilter = "SBDeta_Id=" + SBDeta_Id;
                if (dv.Count > 0)
                {
                    this.tb_SBDeta_PInfo_Id.Text = ValueHandler.GetStringValue(dv[0]["PInfo_Name"]);
                    this.hf_SBDeta_PInfo_Id.Text = ValueHandler.GetStringValue(dv[0]["SBDeta_PInfo_Id"]); 
                    this.nb_SBDeta_Count.Text = ValueHandler.GetIntNumberValue(dv[0]["SBDeta_Count"]).ToString();
                    this.nb_SBDeta_Money.Text = ValueHandler.GetDecNumberValue(dv[0]["SBDeta_Money"]).ToString();
                    this.nb_SBDeta_Price.Text = ValueHandler.GetDecNumberValue(dv[0]["SBDeta_Price"]).ToString();
                    this.btnAdd.Icon = Icon.Accept;
                    this.btnAdd.Text = "确定";
                    this.btnCancle.Hidden = false;
                }
            }
        }

        protected void gv_List_PageIndexChange(object sender, ExtAspNet.GridPageEventArgs e)
        {
            gv_List.PageIndex = e.NewPageIndex;
        }

        #endregion

        #region Method
        private void InitControl()
        {
            bnClose.OnClientClick = ExtAspNet.ActiveWindow.GetHideReference();
            if (Request["Id"] != null)
            {
                Id = ValueHandler.GetIntNumberValue(Request["Id"]);
            }
            //经办人
            SysUsersOp userManager = new SysUsersOp();
            DataTable dtUser = userManager.GetList("");
            this.ddl_SBill_User.DataSource = dtUser;
            this.ddl_SBill_User.DataBind();
            this.ddl_SBill_User.Items.Insert(0, new ExtAspNet.ListItem("-未选择-", "-1"));

            //销售单类型
            BaseDataOp BaseManager = new BaseDataOp();
            DataTable dtList1 = BaseManager.GetList("BData_Type=4");
            this.ddl_SBill_Type.DataSource = dtList1;
            this.ddl_SBill_Type.DataBind();
            this.ddl_SBill_Type.Items.Insert(0, new ExtAspNet.ListItem("-未选择-", "-1"));
            //结算方式

            this.ddl_SBill_PayType.DataSource = LinkService.GetPayType();
            this.ddl_SBill_PayType.DataBind();
            this.ddl_SBill_PayType.Items.Insert(0, new ExtAspNet.ListItem("-未选择-", "-1"));
            //结算状态
            //this.ddl_SBill_State.DataSource = LinkService.GetSBill_State();
            //this.ddl_SBill_State.DataBind();
            //this.ddl_SBill_State.Items.Insert(0, new ExtAspNet.ListItem("-未选择-", "-1"));
            //账户
            AccountListOp AccountManager = new AccountListOp();
            DataTable dtAccountList= AccountManager.GetList("");
            this.ddl_SBill_AList_Id.DataSource = dtAccountList;
            this.ddl_SBill_AList_Id.DataBind();
            this.ddl_SBill_AList_Id.Items.Insert(0, new ExtAspNet.ListItem("-未选择-", "-1"));


        }
        private void GetAndBind()
        {
            SModel.SBill_Id = Id;
            dtDetail = Manager.GetDetail(SModel);
              
            gv_List.DataSource = dtDetail;
            gv_List.DataBind();
            gv_List.RecordCount = dtDetail.Rows.Count;
            if (Id != 0)
            {
                this.tb_SBill_Code.Text = SModel.SBill_Code;
                this.tb_SBill_Code2.Text = SModel.SBill_Code2;
                CustomerOp customerManager = new CustomerOp();
                Customer cust = new Customer();
                cust.Cust_Id = SModel.SBill_Cust_Id;
                customerManager.GetModel(cust);
                this.tb_SBill_Cust_Id.Text = cust.Cust_Name ; 
                this.hf_SBill_Cust_Id.Text = SModel.SBill_Cust_Id.ToString();
                this.tb_SBill_Remark.Text = SModel.SBill_Remark;
                this.ddl_SBill_AList_Id.SelectedValue = SModel.SBill_AList_Id.ToString();
                this.ddl_SBill_PayType.SelectedValue = SModel.SBill_PayType.ToString();
                this.ddl_SBill_Type.SelectedValue = SModel.SBill_Type.ToString();
                this.ddl_SBill_User.SelectedValue = SModel.SBill_User.ToString();
                this.dp_SBill_Date.Text = SModel.SBill_Date.ToString("yyyy-MM-dd");
                this.nb_SBill_Money.Text = SModel.SBill_Money.ToString();
                this.nb_SBill_RealMoney.Text = SModel.SBill_RealMoney.ToString();
                this.nb_SBill_TaxMoney.Text = SModel.SBill_TaxMoney.ToString();
                //未结算
                if (SModel.SBill_State == 0)
                {
                    bnSave.Enabled = true;
                    bnInput.Enabled = true;
                }
                else//已入库
                {
                    bnSave.Enabled = false;
                    bnInput.Enabled = false;
                    btnAdd.Enabled = false;
                    SimpleForm2.Hidden = true;
                    gv_List.Columns[6].Hidden = true;
                    gv_List.Columns[7].Hidden = true;
                }
                if (SModel.SBill_State == 1)
                {
                    this.lb_SBill_State.Text = "<span style='color:Green;font-weight:bold;'>已结算</span>";
                    this.bnSave.Enabled = false;
                }
                else
                    this.lb_SBill_State.Text = "<span style='color:Red;font-weight:bold;'>未结算</span>";


            }
            else
            {
                this.tb_SBill_Code.Text = Coder.CreateCoder(EMenuList.销售管理);
                this.bnInput.Enabled = false;
            }
        }

        #endregion

        #region Property
        SaleBillOp Manager = new SaleBillOp();
        new Sale_Model.SaleBill SModel = new Sale_Model.SaleBill();
        public DataTable dtDetail
        {
            get
            {
                return ViewState["dtDetail"] as DataTable;
            }
            set
            {
                ViewState["dtDetail"] = value;
            }
        }
        /// <summary>
        /// 子表当前编辑的关键子
        /// </summary>
        public int SBDeta_Id
        {
            get
            {
                return ValueHandler.GetIntNumberValue(ViewState["SBDeta_Id"]);
            }
            set
            {
                ViewState["SBDeta_Id"] = value;
            }
        }
        #endregion
    }
}
